﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WP.Modules;
using WP.DB;
using WP.Controls;
using WP.Commons;
using WP.Controls.GridColumn;
using System.Collections;

namespace WP.IM.Form
{
    public partial class frmImCategroyWKWorkCost : BaseQryRpt 
    {
        public frmImCategroyWKWorkCost()
        {
            InitializeComponent();
            LoadAllControl(new ArrayList(this.Controls));
            this.MinimumSize = this.Size;
            InitGridDtl();
        }
        private bool mPressExit = false;
        private bool mblnSettingStatus = false;
        private bool[] mDtlColumnReadOnlyArray;
        private bool m_bCanTrigerCellValueChangedEven = false;
        private bool m_bSettingStatus = false;
        private bool m_bDtlChanged = false;
        private System.Windows.Forms.DataGridView.HitTestInfo mhtiDtl = null;
        private DBAccess mdbcon = new DBAccess(false, false);
        private string mstrTableName = "imCategoryWKWorkCost";
        private enum DtlCol
        {
            RowSeqNo=0,
            CategoryID,
            CategoryName,
            WKProductID,
            WKName,            
            WKRemark,
            WorkCost,
            RecID,
            ValueChanged,
            DelButton
        }

        protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData) //激活回车键
        {
            int WM_KEYDOWN = 256;
            int WM_SYSKEYDOWN = 260;
            if (!(msg.Msg == WM_KEYDOWN | msg.Msg == WM_SYSKEYDOWN))
            {
                return false;
            }

            bool blnRet = false;
            if (BaseFunctions.TrigerKeyEventByControl(this.ActiveControl, this.dgvDetail.Name))
            {
                blnRet = dgvDetail_KeyDownEvent(keyData);
            }         
            if (!blnRet)
            {
                return base.ProcessCmdKey(ref msg, keyData);
            }
            return blnRet;
        }

        #region GRID
        private void InitGridDtl()
        {

            this.dgvDetail.Columns.Clear();
            this.dgvDetail.Rows.Clear();

            DataGridViewTextBoxColumn colRowSeqNo = new DataGridViewTextBoxColumn();
            colRowSeqNo.HeaderText = "序号";
            colRowSeqNo.Visible = true;
            colRowSeqNo.Name = "RowSeqNo";
            colRowSeqNo.Width = 50;
            colRowSeqNo.ReadOnly = true;
            colRowSeqNo.SortMode = DataGridViewColumnSortMode.NotSortable;
            
            TextLookUpColumn colCategoryID = new TextLookUpColumn();
            colCategoryID.HeaderText = "类别编码";
            colCategoryID.Width = 70;
            colCategoryID.Name = "CategoryID";
            colCategoryID.ReadOnly = false;
            colCategoryID.Visible = true;

            TextLookUpColumn colCategoryName = new TextLookUpColumn();
            colCategoryName.HeaderText = "类别名称";
            colCategoryName.Width = 180;
            colCategoryName.Name = "CategoryName";
            colCategoryName.ReadOnly = true   ;
            colCategoryName.Visible = true ;

            TextLookUpColumn colWKID = new TextLookUpColumn();
            colWKID.HeaderText = "工序编码";
            colWKID.Width = 70;
            colWKID.Name = "WKProductID";
            colWKID.ReadOnly = false;

            TextLookUpColumn colWKName = new TextLookUpColumn();
            colWKName.HeaderText = "工序名称";
            colWKName.Width = 180;
            colWKName.Name = "WKName";
            colWKName.ReadOnly = true ;


            DataGridViewTextBoxColumn colWKRemark = new DataGridViewTextBoxColumn();
            colWKRemark.HeaderText = "工序描述";
            colWKRemark.Width = 130;
            colWKRemark.Name = "WKRemark";
            colWKRemark.ReadOnly = true;

            DataGridViewTextBoxColumn colWorkCost = new DataGridViewTextBoxColumn();
            colWorkCost.HeaderText = "工时费用标准";
            colWorkCost.Width = 130;
            colWorkCost.Name = "WorkCostRate";
            colWorkCost.ReadOnly = false ;
            colWorkCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight ;
            colWorkCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colRecID = new DataGridViewTextBoxColumn();
            colRecID.HeaderText = "RecID";
            colRecID.Visible = false;
            colRecID.Name = "RecID";

            DataGridViewTextBoxColumn colValueChanged = new DataGridViewTextBoxColumn();
            colValueChanged.HeaderText = "ValueChanged";
            colValueChanged.Visible = false;
            colValueChanged.Name = "ValueChanged";

            DataGridViewImageColumn colDel = new DataGridViewImageColumn();
            Bitmap delbitmap = new Bitmap(this.iglSource.Images["del.ico"]);
            colDel.Width = 20;
            colDel.Name = "DelLine";
            colDel.HeaderText = "";
            colDel.Resizable = DataGridViewTriState.False;

            this.dgvDetail.Columns.AddRange(new DataGridViewColumn[] { colRowSeqNo, colCategoryID  ,colCategoryName, colWKID, colWKName, colWKRemark,colWorkCost, colRecID, colValueChanged, colDel });

            mDtlColumnReadOnlyArray = new bool[dgvDetail.Columns.Count];
            string[] ColumnWidthArray = DataFunctions.GetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.Name + "." + this.dgvDetail.Name).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < dgvDetail.Columns.Count; i++)
            {
                mDtlColumnReadOnlyArray[i] = dgvDetail.Columns[i].ReadOnly;
                if (ColumnWidthArray.Length == dgvDetail.Columns.Count) dgvDetail.Columns[i].Width = CvtFunc.ToInt(ColumnWidthArray[i]);
            }

            this.dgvDetail.EditMode = DataGridViewEditMode.EditOnEnter;
            this.dgvDetail.RowTemplate.Height = 20;
            this.dgvDetail.RowHeadersWidth = 23;
            this.dgvDetail.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;
            this.dgvDetail.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;
            this.dgvDetail.ColumnHeadersHeight = 30;
            this.dgvDetail.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            this.dgvDetail.SelectionMode = DataGridViewSelectionMode.CellSelect;
            this.dgvDetail.AllowUserToResizeRows = false;

        }
        private void FillDtl(string strCategoryName)
        {
            string strSql = "";
            string strUserName = "";
            string strRecid = "";
            bool bAccess = false;
            m_bCanTrigerCellValueChangedEven = false;

            this.dgvDetail.Rows.Clear();
            DBAccess dbCon = new DBAccess(false, false);

            if (strCategoryName == "ALL")
            {
                strSql = "select A.*,B.WorkingProcedureName,b.Remark from " + mstrTableName + " A inner join rmWorkingProcedure B on A.WKName=B.WorkingProcedureName order by A.CategoryName, A.WKName";
            }
            else
            {
                strSql = "select A.*,B.WorkingProcedureName,b.Remark from " + mstrTableName + " A inner join rmWorkingProcedure B on A.WKName=B.WorkingProcedureName where CategoryName like '%" + strCategoryName + "%' order by SeqNo";
            }
            DataTable mUserAlertTable = dbCon.GetDataSet(strSql).Tables[0];

            for (int i = 0; i < mUserAlertTable.Rows.Count; i++)
            {
                DataRow dr = mUserAlertTable.Rows[i];
                if (this.dgvDetail.Rows.Count <= i) this.dgvDetail.Rows.Add();
                dgvDetail.Rows[dgvDetail.Rows.Count - 1].Cells[(int)DtlCol.RowSeqNo].Value = dgvDetail.Rows.Count.ToString();
                dgvDetail.Rows[dgvDetail.Rows.Count - 1].Cells[(int)DtlCol.WKProductID].Value = dr["WKProductID"].ToString().TrimEnd();
                dgvDetail.Rows[dgvDetail.Rows.Count - 1].Cells[(int)DtlCol.WKName].Value = dr["WKName"].ToString().TrimEnd();
                dgvDetail.Rows[dgvDetail.Rows.Count - 1].Cells[(int)DtlCol.WKRemark].Value = dr["Remark"].ToString().TrimEnd();
                dgvDetail.Rows[dgvDetail.Rows.Count - 1].Cells[(int)DtlCol.CategoryID].Value = dr["CategoryID"].ToString().TrimEnd();
                dgvDetail.Rows[dgvDetail.Rows.Count - 1].Cells[(int)DtlCol.CategoryName].Value = dr["CategoryName"].ToString().TrimEnd();
                dgvDetail.Rows[dgvDetail.Rows.Count - 1].Cells[(int)DtlCol.WorkCost].Value =BaseFunctions.FormatNumeric( dr["WorkCostRate"].ToString(),"Ns.2");
                dgvDetail.Rows[dgvDetail.Rows.Count - 1].Cells[(int)DtlCol.RecID].Value = CvtFunc.ToInt(dr["RecID"]);
                dgvDetail.Rows[dgvDetail.Rows.Count - 1].Cells[(int)DtlCol.ValueChanged].Value = "0";
            }//
            if (dgvDetail.Rows.Count == 0)
            {
                AddDtlRow(this.dgvDetail.Name);
            }
            dbCon.CloseCon();
            base.SetBlankImage(dgvDetail);
            m_bCanTrigerCellValueChangedEven = true;
        }
        private void dgvDetail_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

            if (dgvDetail.Columns[e.ColumnIndex] is TextLookUpColumn)
            {
                if ((dgvDetail.Columns[e.ColumnIndex] as TextLookUpColumn).CanLookUp())
                {
                    Dtl_LookUp(e.ColumnIndex);
                }
            }
            else
            {
                if (this.dgvDetail.CurrentCell.ColumnIndex == (int)DtlCol.DelButton && base.HasDelImage(this.dgvDetail, e))
                {
                    this.dgvDetail.CurrentCell.Selected = true;
                    this.dgvDetail.CurrentCell.Selected = false;
                    if (!this.Delete_Detail(this.dgvDetail.Rows[this.dgvDetail.CurrentCell.RowIndex]))
                    {
                        return;
                    }
                    this.dgvDetail.Rows.Remove(this.dgvDetail.Rows[this.dgvDetail.CurrentCell.RowIndex]);
                    if (this.dgvDetail.Rows.Count == 0)
                    {
                        this.AddDtlRow(this.dgvDetail.Name);
                    }
                }
            }
        }
        private void AddDtlRow(string strGridName)
        {
            AddDtlRow(strGridName, -1);
        }

        private void AddDtlRow(string strGridName, double iRow)
        {
            if (strGridName == dgvDetail.Name)
            {
                int intRow = CvtFunc.ToInt(iRow);
                m_bCanTrigerCellValueChangedEven = false;
                if (iRow >= 0)
                {
                    intRow++;
                    this.dgvDetail.Rows.Insert(intRow, 1);
                }
                else
                {
                    this.dgvDetail.Rows.Add();
                    intRow = this.dgvDetail.Rows.Count - 1;
                }
                dgvDetail.Rows[intRow].Cells[(int)DtlCol.RowSeqNo].Value = dgvDetail.Rows.Count.ToString();
                dgvDetail.Rows[intRow].Cells[(int)DtlCol.CategoryID].Value = txtCategoryID.Text;
                dgvDetail.Rows[intRow].Cells[(int)DtlCol.CategoryName].Value =( DataFunctions.GetFieldValue ("rmCategory", "CategoryName","CategoryName='"+ txtCategoryName.Text +"'")==""? "":txtCategoryName.Text ) ;
                dgvDetail.Rows[intRow].Cells[(int)DtlCol.WorkCost].Value = "0.00";
                dgvDetail.Rows[intRow].Cells[(int)DtlCol.WKRemark].Value = "";
                dgvDetail.Rows[intRow].Cells[(int)DtlCol.WKName].Value = "";
                dgvDetail.Rows[intRow].Cells[(int)DtlCol.RecID].Value = -1;
                dgvDetail.Rows[intRow].Cells[(int)DtlCol.ValueChanged].Value = "0";
                dgvDetail.CurrentCell = dgvDetail.Rows[intRow].Cells[(int)DtlCol.CategoryID];
                m_bCanTrigerCellValueChangedEven = true;
            }
        }
        private void Dtl_LookUp(int iColumnIndex)
        {
            string strSQL = "", strCaption = "", strFindValue = "", strFindField = "";
            switch ((DtlCol)iColumnIndex)
            {
                case DtlCol.WKProductID :
                    strSQL = WP.Commons.BaseFunctions.GetLookUpSQL("rmWorkingProcedure");
                    strCaption = "工序选择";
                    if (this.dgvDetail.CurrentRow.Cells[(int)DtlCol.WKName].Value != null) strFindValue = this.dgvDetail.CurrentRow.Cells[(int)DtlCol.WKName].Value.ToString();
                    strFindField = "WorkingProcedureID";
                    break;
                case DtlCol.CategoryID :
                    strSQL = WP.Commons.BaseFunctions.GetLookUpSQL("rmCategory");
                    strCaption = "类别选择";
                    if (this.dgvDetail.CurrentRow.Cells[(int)DtlCol.CategoryID].Value != null) strFindValue = this.dgvDetail.CurrentRow.Cells[(int)DtlCol.CategoryID].Value.ToString();
                    strFindField = "CategoryID";
                    break;

            }

            if (strSQL == "") return;
            if (mblnLookUpSortByDescription)
            {
                strSQL = DataFunctions.GetSqlByDescriptionSort(strSQL);
                mblnLookUpSortByDescription = false;
            }

            frmLookUp frmlookup = new frmLookUp(strSQL, strCaption, strFindValue, strFindField);
            frmlookup.ShowDialog();

            if (frmlookup.HaveReturnValue)
            {
                switch ((DtlCol)iColumnIndex)
                {
                    case DtlCol.WKProductID :
                        this.dgvDetail.CurrentRow.Cells[(int)DtlCol.WKProductID].Value = frmlookup.GetReturnValue("WorkingProcedureID");
                        this.dgvDetail.CurrentRow.Cells[(int)DtlCol.WKName].Value = frmlookup.GetReturnValue("WorkingProcedureName");
                        this.dgvDetail.CurrentRow.Cells[(int)DtlCol.WKRemark].Value = frmlookup.GetReturnValue("Remark");
                        break;
                    case DtlCol.CategoryID :
                        this.dgvDetail.CurrentRow.Cells[(int)DtlCol.CategoryID].Value = frmlookup.GetReturnValue("CategoryID");   
                        this.dgvDetail.CurrentRow.Cells[(int)DtlCol.CategoryName].Value = frmlookup.GetReturnValue("CategoryName");                        
                        break;
                }
            }
            frmlookup.Close();
        }
        private bool CheckDtlRow(ref string strErrMsg)
        {
            bool bCheckResult = true;
            for (int i = 0; i < dgvDetail.ColumnCount - 1; i++)
            {

                bCheckResult = CheckDtlCell(i, ref strErrMsg);
                if (!bCheckResult) break;
            }
            string strRecID= CvtFunc.ToString ( this.dgvDetail.CurrentRow.Cells [(int)DtlCol.RecID ].Value) ;
            string strCategoryName = CvtFunc.ToString(this.dgvDetail.CurrentRow.Cells[(int)DtlCol.CategoryID].Value);
            string strWKName = CvtFunc.ToString(this.dgvDetail.CurrentRow.Cells[(int)DtlCol.WKProductID].Value);
            string strSQL = "select * from " + mstrTableName + " where RecID!='" + strRecID + "' and CategoryID='" + strCategoryName + "' and WKProductID='" + strWKName + "'";
            DataRow drCheck = mdbcon.GetDataFirstRow(strSQL);
            if (drCheck != null)
            {
                strErrMsg = "此设置已经存在，不能重复添加。";
                return false;
            }
            return bCheckResult;
        }
        private bool CheckDtlCell(int iColumn, ref string strErrMsg)
        {
            bool bReturnValue = true;
            strErrMsg = "";
            string strValue = "";
            if (this.dgvDetail.CurrentRow != null && this.dgvDetail.CurrentRow.Cells[iColumn].Value != null)
            {
                strValue = this.dgvDetail.CurrentRow.Cells[iColumn].Value.ToString().TrimEnd();
            }
            switch ((DtlCol)iColumn)
            {
                case DtlCol.CategoryName:
                    if (strValue.Trim() == "")
                    {
                        strErrMsg = "类别名称不能空.";
                        return false;
                    }
                    if (!DataFunctions.CheckRecordExist("rmCategory", strValue, "CategoryName"))
                    {
                        strErrMsg = "不存在的类别名称";
                        return false;
                    }
                    return true;
                case DtlCol.WKProductID:
                    if (strValue.Trim() == "")
                    {
                        strErrMsg = "工序不能空.";
                        return false;
                    }
                    if (!DataFunctions.CheckRecordExist("rmWorkingProcedure", strValue, "WorkingProcedureID"))
                    {
                        strErrMsg = "不存在的工序";
                        return false;
                    }
                    return true;
                case DtlCol.WKName:
                    if (strValue.Trim() == "")
                    {
                        strErrMsg = "工序名称不能空.";
                        return false;
                    }
                    if (!DataFunctions.CheckRecordExist("rmWorkingProcedure", strValue, "WorkingProcedureName"))
                    {
                        strErrMsg = "不存在的工序名称";
                        return false;
                    }
                    return true;
            }
            return bReturnValue;
        }
        private void dgvDetail_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (dgvDetail.CurrentRow == null)
            {
                e.Cancel = false;
                return;
            }
            if (int.Parse(dgvDetail.CurrentRow.Cells[(int)DtlCol.RecID].Value.ToString()) > 0 && int.Parse(dgvDetail.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value.ToString()) == 0)
            {
                e.Cancel = false;
                return;

            }

            if (mhtiDtl != null && mhtiDtl.ColumnIndex == (int)DtlCol.DelButton)
            {
                mhtiDtl = null;
                return;
            }


            if (this.dgvDetail.CurrentCell.ColumnIndex == (int)DtlCol.DelButton)
            {
                e.Cancel = false;
                return;

            }
            string strErrMsg = "";
            if (!BaseFunctions.NeedValidGridCell(this.ActiveControl, "dgvDetail") || m_bSettingStatus || !m_bCanTrigerCellValueChangedEven)
            {
                e.Cancel = false;
                return;
            }

            e.Cancel = !CheckDtlCell(e.ColumnIndex, ref strErrMsg);
            if (strErrMsg != "")
            {
                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
        private void dgvDetail_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (dgvDetail.CurrentRow != null && int.Parse(dgvDetail.CurrentRow.Cells[(int)DtlCol.RecID].Value.ToString()) > 0 && int.Parse(dgvDetail.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value.ToString()) == 0)
            {
                e.Cancel = false;
                return;

            }

            string strErrMsg = "";
            if (!BaseFunctions.NeedValidGridCell(this.ActiveControl, "dgvDetail") || m_bSettingStatus || !m_bCanTrigerCellValueChangedEven)
            {
                e.Cancel = false;
                return;
            }
            e.Cancel = !CheckDtlRow(ref strErrMsg);
            if (strErrMsg != "")
            {
                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

        }
        private void dgvDetail_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (!m_bCanTrigerCellValueChangedEven || e.ColumnIndex == (int)DtlCol.ValueChanged || e.ColumnIndex == (int)DtlCol.DelButton) return;
            dgvDetail.Rows[e.RowIndex].Cells[(int)DtlCol.ValueChanged].Value = "1";
            m_bDtlChanged = true;
            dgvDetail.EndEdit();
            if (e.ColumnIndex == (int)DtlCol.CategoryID)
            {
                string strCategoryID = CvtFunc.ToString(this.dgvDetail.CurrentRow.Cells[(int)DtlCol.CategoryID].Value);
                this.dgvDetail.CurrentRow.Cells[(int)DtlCol.CategoryName].Value = DataFunctions.GetFieldValue("rmCategory", "CategoryName", "CategoryID='" + strCategoryID + "'");
            }
            if (e.ColumnIndex == (int)DtlCol.WKProductID)
            {
                string strWKName = CvtFunc.ToString(this.dgvDetail.CurrentRow.Cells[(int)DtlCol.WKProductID].Value);
                this.dgvDetail.CurrentRow.Cells[(int)DtlCol.WKName].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "WorkingProcedureName", "WorkingProcedureID='" + strWKName + "'");
                this.dgvDetail.CurrentRow.Cells[(int)DtlCol.WKRemark].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "Remark", "WorkingProcedureID='" + strWKName + "'");
            }
            dgvDetail.EndEdit();
        }
        private void dgvDetail_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgvDetail.CurrentCell.ColumnIndex == (int)DtlCol.DelButton)
            {
                this.dgvDetail.CurrentCell.Selected = false;
            }
            if ( CvtFunc.ToDouble (this.dgvDetail.Rows[this.dgvDetail.CurrentCell.RowIndex].Cells[(int)DtlCol.RecID].Value) > 0)
            {
                this.dgvDetail.Rows[this.dgvDetail.CurrentCell.RowIndex].Cells[(int)DtlCol.CategoryName].ReadOnly = true;
            }
        }
        private void dgvDetail_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgvDetail.CurrentCell.ColumnIndex == (int)DtlCol.DelButton)
            {
                this.dgvDetail.CurrentCell.Selected = false;
            }
        }
        private void dgvDetail_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            return;
        }
        private void dgvDetail_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            base.SetGridViewDelImage(this.dgvDetail, e, (int)DtlCol.DelButton);
            string strErrMsg = "";
            if (dgvDetail.CurrentRow != null && CvtFunc.ToInt(dgvDetail.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) > 0)
            {
                if (CheckDtlRow(ref strErrMsg))
                {
                    if (!Update_Detail(this.dgvDetail.Rows[this.dgvDetail.CurrentCell.RowIndex]))
                    {
                        return;
                    }
                  
                     //AddDtlRow(this.dgvDetail.Name);
                }
                else
                {
                    return;
                }
            }
        }
        private void dgvDetail_MouseDown(object sender, MouseEventArgs e)
        {

            mhtiDtl = this.dgvDetail.HitTest(e.X, e.Y);

            //System.Windows.Forms.DataGridView.HitTestInfo hti;
            //hti = this.dgvDetail.HitTest(e.X, e.Y);
            //switch (hti.Type)
            //{
            //    case System.Windows.Forms.DataGridViewHitTestType.Cell:
            //        break;
            //}
        }
        private bool dgvDetail_KeyDownEvent(System.Windows.Forms.Keys keyData)
        {
            string strErrMsg = "";
            int j;
            switch (keyData)
            {
                case Keys.Down:
                    #region Key Down

                    this.dgvDetail.EndEdit();
                    if (CvtFunc.ToInt(dgvDetail.CurrentRow.Cells[(int)DtlCol.RecID].Value) > 0)
                    {
                        if (CvtFunc.ToInt(dgvDetail.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) > 0)
                        {

                            if (CheckDtlRow(ref strErrMsg))
                            {

                                if (!Update_Detail(this.dgvDetail.Rows[this.dgvDetail.CurrentCell.RowIndex]))
                                {
                                    return true;
                                }
                            }
                            else
                            {
                                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return true;
                            }
                        }
                        if (dgvDetail.CurrentCell.RowIndex < dgvDetail.Rows.Count - 1)
                        {
                            dgvDetail.CurrentCell = this.dgvDetail.Rows[dgvDetail.CurrentCell.RowIndex + 1].Cells[(int)DtlCol.WKName];
                        }
                        else
                        {
                            AddDtlRow(this.dgvDetail.Name);
                        }
                    }
                    else
                    {
                        if (CheckDtlRow(ref strErrMsg))
                        {
                            if (!Update_Detail(this.dgvDetail.Rows[this.dgvDetail.CurrentCell.RowIndex]))
                            {
                                return true;
                            }
                            AddDtlRow(this.dgvDetail.Name);
                        }
                        else
                        {
                            MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            return true;
                        }
                    }
                    return true;


                    #endregion
                case Keys.Up:
                    #region Key Up
                    if (CvtFunc.ToInt(dgvDetail.CurrentRow.Cells[(int)DtlCol.RecID].Value) > 0)
                    {
                        if (CvtFunc.ToInt(dgvDetail.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) > 0)
                        {
                            if (CheckDtlRow(ref strErrMsg))
                            {
                                if (!Update_Detail(this.dgvDetail.Rows[this.dgvDetail.CurrentCell.RowIndex])) return true;
                            }
                            else
                            {
                                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return true;
                            }
                        }
                        if (dgvDetail.CurrentCell.RowIndex > 0)
                        {
                            dgvDetail.CurrentCell = this.dgvDetail.Rows[dgvDetail.CurrentCell.RowIndex - 1].Cells[(int)DtlCol.WKName];
                        }
                    }
                    else
                    {
                        if (CheckDtlRow(ref strErrMsg))
                        {
                            if (!Update_Detail(this.dgvDetail.Rows[this.dgvDetail.CurrentCell.RowIndex])) return true;
                            if (dgvDetail.CurrentCell.RowIndex > 0)
                            {
                                dgvDetail.CurrentCell = this.dgvDetail.Rows[dgvDetail.CurrentCell.RowIndex - 1].Cells[(int)DtlCol.WKName];
                            }
                        }
                        else if (dgvDetail.Rows.Count > 1)
                        {

                            this.dgvDetail.Rows.Remove(this.dgvDetail.CurrentRow);
                            dgvDetail.CurrentCell = this.dgvDetail.Rows[dgvDetail.Rows.Count - 1].Cells[(int)DtlCol.WKName];
                        }
                    }
                    return true;
                    #endregion
                case Keys.Enter:
                    #region Key Enter
                    this.dgvDetail.EndEdit();
                    j = BaseFunctions.GetGridViewLastEnabledEditColumn(this.dgvDetail);
                    if (dgvDetail.CurrentCell.ColumnIndex == j)
                    {
                        if (CvtFunc.ToInt(dgvDetail.CurrentRow.Cells[(int)DtlCol.RecID].Value) > 0)
                        {
                            if (CvtFunc.ToInt(dgvDetail.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) > 0)
                            {
                                if (CheckDtlRow(ref strErrMsg))
                                {
                                    if (!Update_Detail(this.dgvDetail.Rows[this.dgvDetail.CurrentCell.RowIndex])) return true;
                                }
                                else
                                {
                                    MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                    return true;
                                }
                            }
                        }
                        else
                        {
                            if (CheckDtlRow(ref strErrMsg))
                            {
                                if (!Update_Detail(this.dgvDetail.Rows[this.dgvDetail.CurrentCell.RowIndex])) return true;
                            }
                            else
                            {
                                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return true;
                            }

                        }
                        if (dgvDetail.CurrentCell.RowIndex < dgvDetail.Rows.Count - 1)
                        {
                            dgvDetail.CurrentCell = this.dgvDetail.Rows[dgvDetail.CurrentCell.RowIndex + 1].Cells[(int)DtlCol.WKName];
                        }
                        else
                        {
                            AddDtlRow(this.dgvDetail.Name);
                        }
                    }
                    else
                    {
                        j = BaseFunctions.GetGridViewNextEnabledEditColumn(dgvDetail, dgvDetail.CurrentCell.ColumnIndex);
                        if (j >= 0) SendKeys.Send("{Tab}");
                        //  if (j >= 0) dgvDetail.CurrentCell = this.dgvDetail.Rows[dgvDetail.CurrentCell.RowIndex].Cells[j];
                    }

                    return true;
                    #endregion
            }
            return false;
        }
        private bool Update_Detail(DataGridViewRow dgvRow)
        {
            if (dgvRow == null) return false;
            string strSQL = string.Empty;
            DBAccess dbcon = new DBAccess(false, false);
            string strFields = "SeqNo,CategoryID,CategoryName,WKProductID,WKName,WorkCostRate";
            try
            {
                DataRow drDtl = dbcon.GetDataTable("select * from " + mstrTableName + " ").NewRow();
                if (CvtFunc.ToDouble(dgvRow.Cells[(int)DtlCol.RecID].Value) > 0)   //Update
                {
                    BaseFunctions.FillDataRowByGridRow(dgvRow, drDtl);
                    DataFunctions.UpdateTable(dbcon, strFields, mstrTableName , drDtl, FormStatus.Update);
                }
                else //Add New
                {
                    BaseFunctions.FillDataRowByGridRow(dgvRow, drDtl);
                    DataFunctions.UpdateTable(dbcon, strFields, mstrTableName, drDtl, FormStatus.AddNew);
                    dgvRow.Cells[(int)DtlCol.RecID].Value = CvtFunc.ToString(drDtl["RecID"]);
                }
                dbcon.CloseCon();
            }
            catch (Exception ex)
            {
                dbcon.CloseCon();
                return false;
            }
            return true;
        }
        private bool Delete_Detail(DataGridViewRow dgvRow)
        {
            if (dgvRow == null) return true;
            string strRecID = CvtFunc.ToString(dgvRow.Cells[(int)DtlCol.RecID].Value);
            string strSeqNo = CvtFunc.ToString(dgvRow.Cells[(int)DtlCol.RowSeqNo].Value);
            string strSQL = string.Empty;
            if (CvtFunc.ToDouble(strRecID) > 0)
            {
                if (MessageBox.Show("您确定要删除？", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    DBAccess dbcon = new DBAccess(false, false);
                    try
                    {
                        dbcon.BeginTran();
                        strSQL = "Delete "+ mstrTableName +" where RecID='" + strRecID + "'";
                        dbcon.ExecuteSql(strSQL);
                        dbcon.CommitTran();
                    }
                    catch (Exception ex)
                    {
                        dbcon.RollbackTran();
                    }
                    dbcon.CloseCon();
                }
            }
            return true;
        }

        private void LookUp_Click(object sender, EventArgs e)
        {
            string strFindValue = string.Empty;
            string strFieldName = string.Empty;
            string strSql = string.Empty;
            string strCaption = string.Empty;
            Control con = sender as Control;
            if (con == null) return;
            Control ocon = null;
            switch (con.Name)
            {
                case "ubtCategoryName":
                    strFindValue = txtCategoryName.Text;
                    strFieldName = "CategoryID";
                    strCaption = "类别 选择";
                    strSql = BaseFunctions.GetLookUpSQL("rmCategory");
                    ocon = txtCategoryID;
                    break;
            }
            if (mblnLookUpSortByDescription) strSql = DataFunctions.GetSqlByDescriptionSort(strSql);
            mblnLookUpSortByDescription = false;

            frmLookUp frmlookup = new frmLookUp(strSql, strCaption, strFindValue, strFieldName);
            frmlookup.ShowDialog();
            if (frmlookup.HaveReturnValue)
            {
                ocon.Text = frmlookup.GetReturnValue(strFieldName);
                txtCategoryName.Text = frmlookup.GetReturnValue("CategoryName");
                ocon.Focus();
            }
            frmlookup.Close();

        }
        #endregion

        private void txtCategoryName_TextChanged(object sender, EventArgs e)
        {                      
            FillDtl(txtCategoryName.Text);
        }

        private void txtCategoryName_Validating(object sender, CancelEventArgs e)
        {
            if (txtCategoryName.Text == "" && this.dgvDetail.Rows.Count == 0) return;
            //if (!mPressExit)
            //{
            //    if (txtCategoryName.Text == "") e.Cancel = true;
            //}
        }

        private void dgvDetail_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            this.dgvDetail.EndEdit();

            if (e.ColumnIndex == (int)DtlCol.WKName || e.ColumnIndex == (int)DtlCol.WorkCost )
            {
                string strErrMsg = string.Empty;
                if (CheckDtlRow(ref strErrMsg))
                {
                    Update_Detail(this.dgvDetail.Rows[e.RowIndex]);
                }
            }
            if (e.ColumnIndex == (int)DtlCol.WKName)
            {
                this.dgvDetail.Rows[e.RowIndex].Cells[(int)DtlCol.WKRemark].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "Remark", "WorkingProcedureName='" + CvtFunc.ToString(this.dgvDetail.CurrentRow.Cells[(int)DtlCol.WKName].Value) + "'");
            }
            else if (e.ColumnIndex == (int)DtlCol.WorkCost)
            {
                this.dgvDetail.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvDetail.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.2");
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            mPressExit = true;
            this.Close();
        }

        private void btnHelp_Click(object sender, EventArgs e)
        {
            mPressExit = true;
            base.OnHelp();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            string strErrMsg = string.Empty;
            if (CheckDtlRow(ref strErrMsg))
            {
                Update_Detail(this.dgvDetail.CurrentRow );
                //this.Close();
            }
        }

        private void btnToExcel_Click(object sender, EventArgs e)
        {

             string strSQL="select WKName,CategoryName,WorkCostRate,RecID from imCategoryWKWorkCost where categoryid='"+ txtCategoryID.Text  +"'";
            DataView dv = mdbcon.GetDataTable ( strSQL ).DefaultView;
            ToExcel.DataGirdViewToExcel( this.dgvDetail);
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            txtCategoryName.Text = "";
            txtCategoryID.Text = "";
            FillDtl("ALL");
        }

        private void btn_CopyTo_Click(object sender, EventArgs e)
        {
            string strSQL = "";
            string strFindValue = string.Empty;
            string strFieldName = string.Empty;
            string strSql = string.Empty;
            string strCaption = string.Empty;
            string strDestCategory = "";
            string strDestCategoryID = "";
            string strOrigCategory = "";
            string strOrigCategoryID = "";

            if (this.dgvDetail.CurrentRow == null) return;
            strOrigCategoryID = CvtFunc.ToString(this.dgvDetail.CurrentRow.Cells[(int)DtlCol.CategoryID].Value);
            strOrigCategory = CvtFunc.ToString(this.dgvDetail.CurrentRow.Cells[(int)DtlCol.CategoryName].Value);
            strFindValue = strOrigCategory;
            strFieldName = "CategoryID";
            strCaption = "复制  类别名称：" + strOrigCategory + " 到 ";
            strSql = BaseFunctions.GetLookUpSQL("rmCategory");

            if (mblnLookUpSortByDescription) strSql = DataFunctions.GetSqlByDescriptionSort(strSql);
            mblnLookUpSortByDescription = false;

            frmLookUp frmlookup = new frmLookUp(strSql, strCaption, strFindValue, strFieldName);
            frmlookup.ShowDialog();
            if (frmlookup.HaveReturnValue)
            {
                strDestCategoryID = frmlookup.GetReturnValue(strFieldName);
                strDestCategory = frmlookup.GetReturnValue("CategoryName");
            }
            else 
            {
                return;
            }
            frmlookup.Close();

            if (strDestCategoryID == strOrigCategoryID)
            {
                MsgBoxEx.Show("目标类别不能和源类别相同", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                strSQL = " insert into imCategoryWKWorkCost (WKProductID,WKName,CategoryID,CategoryName,WorkCostRate) ";
                strSQL += "select WKProductID,WKName,'" + strDestCategoryID + "','"+ strDestCategory +"',WorkCostRate from imCategoryWKWorkCost where categoryID='" + strOrigCategoryID + "'";
                strSQL += " and WKName not in (select WKName from imCategoryWKWorkCost where categoryID='" + strDestCategoryID + "')";
                DBAccess dbcon = new DBAccess(false, false);
                dbcon.ExecuteSql(strSQL);
                dbcon.CloseCon();
                if (txtCategoryName.Text == "")
                {
                    FillDtl("ALL");
                }
                else
                {
                    FillDtl(txtCategoryName.Text);
                }
            }
        }

    }
}
